package com.iflytek.elpmobile.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

public class BitmapUtils 
{
	private final static String TAG = BitmapUtils.class.getSimpleName();

	private static int sWidth = 128;
	private static int sHeight = 128;

	public static void setScale(int scale)
	{
		int w = 128;
		int h = 128;
		sWidth = w * scale;
		sHeight = h * scale;
	}
	
	public static void setSize(int width, int height) {
		int size = width > height ? width : height;
		sWidth = size;
		sHeight = size;
	}

	public static Bitmap getBitmap(byte[] coverByte) 
	{
		try {
			if (coverByte == null)
				return null;

			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(coverByte, 0, coverByte.length,
			opts);
			opts.inSampleSize = BitmapUtils.computeSampleSize(opts, -1, sWidth
					* sHeight);

			opts.inJustDecodeBounds = false;
			return BitmapFactory.decodeByteArray(coverByte, 0,
					coverByte.length, opts);
		}
		catch (Exception ex) 
		{
			ex.printStackTrace();
		}

		return null;
	}
	
	public static Bitmap getBitmap(InputStream is) 
	{
		try {
			if (is == null)
				return null;
			
			int size = is.available();
			byte [] bs = new byte[size];
			is.read(bs, 0, bs.length);
			
			return getBitmap(bs);			
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
		}

		return null;	
	}

	public static Bitmap getBitmap(String path, PackageUtils.FilePosition pos) 
	{
		if (StringUtils.isEmpty(path))
			return null;
		else if (pos == null)
			return null;

		byte[] buffer = ReadFileUtils.getBuffer(path, pos.getOffset(),
				pos.getSize());

		return getBitmap(buffer);
	}

	public static Bitmap getBitmap(String path) {
		if (StringUtils.isEmpty(path))
			return null;

		byte[] buffer = ReadFileUtils.getBuffer(path);

		return getBitmap(buffer);
	}
	
	public static Bitmap getImageFromNet(String path) throws IOException 
	{  
		Bitmap bitmap = null;
	    HttpGet httpGet = new HttpGet(path);                           //创建一个GET方式的HttpRequest对象
	    DefaultHttpClient httpClient = new DefaultHttpClient();        //创建一个默认的HTTP客户端
	    try {
	    	HttpResponse httpResponse = httpClient.execute(httpGet);               //执行GET方式的HTTP请求
	        int reponseCode = httpResponse.getStatusLine().getStatusCode();        //获得服务器的响应码
	        if(reponseCode == HttpStatus.SC_OK) 
	        {
		        InputStream inputStream = httpResponse.getEntity().getContent();   //获得服务器的响应内容
		        bitmap = BitmapFactory.decodeStream(inputStream);
		        inputStream.close();
	        }
	     }catch (Exception e) {
	    	 e.printStackTrace();
	     }
	     return bitmap;
	}
	
	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) 
	{
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8)
		{
			roundedSize = 1;
			while (roundedSize < initialSize) 
			{
				roundedSize <<= 1;
			}
		}
		else
		{
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) 
	{
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) 
		{
			return 1;
		} 
		else if (minSideLength == -1) 
		{
			return lowerBound;
		} 
		else 
		{
			return upperBound;

		}
	}

	// 将图片保存到指定路径
	public static boolean saveFile(Bitmap bm, String path)
	{
		if (bm == null || path == null)
			return false;
		
		try 
		{
			File myCaptureFile = new File(path);
			if (myCaptureFile.exists()) 
			{
				if (!myCaptureFile.delete()) {
					Log.e(TAG, "删除头像临时文件失败");
					return false;
				}
			}
			
			if (myCaptureFile.createNewFile()) 
			{
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(myCaptureFile));
				bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
				bos.flush();
				bos.close();
				
				return true;
			}
		}
		catch (FileNotFoundException e) 		
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	* 转换图片成圆形
	* @param bitmap 传入Bitmap对象
	* @return
	*/
	public static Bitmap toRoundBitmap(Bitmap bitmap) 
	{
		int width = bitmap.getWidth();
	    int height = bitmap.getHeight();
		float roundPx;
		float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
		if (width <= height) 
		{
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} 
		else 
		{
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();

		final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
		final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}
	
	public static Bitmap readBitmap(Context context, int resId)
	{
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
}
